﻿using BW.Demo.Infrastructure.Interfcaes;
using BW.Demo.WebApi.BaseDbContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BW.Demo.Infrastructure.Implement
{
    public class BaseRespitory<T>:IBaseRespitory<T> where T : class
    {
        private readonly DemoContext _db;
        public BaseRespitory(DemoContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="t">实体对象</param>
        /// <returns>受影响行数</returns>
        public async Task<int> CreateAsync(T t)
        {
            await _db.Set<T>().AddAsync(t);
            return await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量新增实体集合
        /// </summary>
        /// <param name="t">食堂集合</param>
        /// <returns>受影响行数</returns>
        public async Task<int> CreateRangeAsync(List<T> t)
        {
            _db.Set<T>().AddRange(t);
            return await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 查询全部实体表达式
        /// </summary>
        /// <returns></returns>
        public  IQueryable<T> GetAll()
        {
            return _db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 根据Id获取单个实体
        /// </summary>
        /// <param name="id">指定的实体Id</param>
        /// <returns></returns>
        public async Task<T> GetModel(long id)
        {
            return await _db.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="t">实体对象</param>
        /// <returns>受影响行数</returns>
        public async Task<int> UpdateAsync(T t)
        {
            _db.Set<T>().Update(t);
            return await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改实体集合
        /// </summary>
        /// <param name="t">食堂集合</param>
        /// <returns>受影响行数</returns>
        public async Task<int> UpdateRangeAsync(List<T> t)
        {
            _db.Set<T>().UpdateRange(t);
            return await _db.SaveChangesAsync();
        }
    }
}
